#!/usr/bin/env python
# coding=utf-8

from HTMLParser import HTMLParser
from re import sub
from sys import stderr
from traceback import print_exc
import hashlib
from config import MyConfObj


class DeHTMLParser(HTMLParser):

    def __init__(self):
        HTMLParser.__init__(self)
        self.__text = []

    def handle_data(self, data):
        text = data.strip()
        if len(text) > 0:
            text = sub('[ \t\r\n]+', ' ', text)
            self.__text.append(text + ' ')

    def handle_starttag(self, tag, attrs):
        if tag == 'p':
            self.__text.append('\n\n')
        elif tag == 'br':
            self.__text.append('\n')

    def handle_startendtag(self, tag, attrs):
        if tag == 'br':
            self.__text.append('\n\n')

    def text(self):
        return ''.join(self.__text).strip()


def dehtml(text):
    try:
        parser = DeHTMLParser()
        parser.feed(text)
        parser.close()
        return parser.text()
    except:
        print_exc(file=stderr)
        return text


def html2textile(html):
    return dehtml(html)


def is_chinese(text):
    if text:
        for uchar in text:
            if uchar >= u'\u4e00' and uchar <= u'\u9fa5':
                return True
    return False


def create_md5(args):
    md5_constructor = hashlib.md5
    return md5_constructor(args).hexdigest()


def admin_pwd_digest(passwd):
    """
    用户加密密码处理
    :param passwd:
    :return:
    """
    ttt = MyConfObj.ADMIN_SECRET + passwd
    return create_md5(ttt)


def user_pwd_digest(passwd):
    """

    :param passwd:
    :return:
    """
    ttt = MyConfObj.USER_SECRET + passwd
    return create_md5(ttt)